package controller

import (
	"commons/enums/sysCode"
	"commons/handler/request"
	"commons/handler/response"
	"commons/output/jsonError"
	"commons/output/jsonSuccess"
	"commons/util/convertUtil"
	"commons/util/tokenUtil"
	"imi/model/userModel"
	"time"
)

type UserController struct {
	BaseController
}

//登陆
func (u *UserController) Login() response.Handle {
	from := request.GetPost()
	var (
		userNickname = convertUtil.String(from["userNickname"])
		userPass     = convertUtil.String(from["userPass"])
	)
	if len(userNickname) == 0 {
		return jsonError.Write(sysCode.Code.ERROR, "账户不能为空", nil)
	}
	if len(userPass) == 0 {
		return jsonError.Write(sysCode.Code.ERROR, "密码不能为空", nil)
	}
	user, err := userModel.GetUserNickName(userNickname)
	if err != nil {
		return jsonError.Write(sysCode.Code.ERROR, "账户不存在", nil)

	}
	if user.UserPass != userModel.UserPassword(userPass) {
		return jsonError.Write(sysCode.Code.ERROR, "密码错误", nil)
	}
	u.userInfo.Id = user.Id
	u.userInfo.Avatar = user.Avatar
	u.userInfo.UserNickname = user.UserNickname
	token := tokenUtil.Create(u.userInfo)
	user.AccessToken = token
	user.LastLoginTime = int(time.Now().Unix())
	_, err = userModel.UpdateToken(user)
	if err != nil {
		return jsonError.Write(sysCode.Code.ERROR, "登陆失败", "")

	}
	user.UserPass = ""
	return jsonSuccess.Write(sysCode.Code.SUCCESS, "登陆成功", user)

}

//注册
func (u *UserController) Register() response.Handle {
	from := request.GetPost()
	var (
		userNickname = convertUtil.String(from["userNickname"])
		userPass     = convertUtil.String(from["userPass"])
		sex          = convertUtil.Int(from["sex"])
		avatar       = convertUtil.String(from["avatar"])
		ip           = convertUtil.String(from["ip"])
	)
	_, _ = userModel.Register(userNickname, userPass, sex, avatar, ip)
	return jsonSuccess.Write(sysCode.Code.SUCCESS, "", from)
}
